﻿using adfly;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WPFWebControl;

namespace AutoCreateLink
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : System.Windows.Window, INotifyPropertyChanged
    {      
        public MainWindow()
        {
            InitializeComponent();
            HideScriptErrors(wb, true);
            //_listLinks = new ObservableCollection<bannerItem>();
            DataContext = this;

        }

        public void HideScriptErrors(System.Windows.Controls.WebBrowser wb, bool hide)
        {
            var fiComWebBrowser = typeof(System.Windows.Controls.WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
            if (fiComWebBrowser == null) return;
            var objComWebBrowser = fiComWebBrowser.GetValue(wb);
            if (objComWebBrowser == null)
            {
                wb.Loaded += (o, s) => HideScriptErrors(wb, hide); //In case we are to early
                return;
            }
            objComWebBrowser.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, objComWebBrowser, new object[] { hide });
        }


        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }


        List<linkWeb> _listLinks;
        public List<linkWeb> ListLinks
        {
            get
            {
                return _listLinks;
            }
            set
            {
                if (_listLinks != value)
                {
                    _listLinks = value;
                    OnPropertyChanged("ListLinks");
                }
            }
        }

        private linkWeb activeLink;
        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            if (ListLinks.Count > 0)
            {
                activeLink = ListLinks.ElementAt(0);
                nextItem();
            }
        }

        [DllImport("KERNEL32.DLL", EntryPoint = "SetProcessWorkingSetSize", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
        internal static extern bool SetProcessWorkingSetSize(IntPtr pProcess, int dwMinimumWorkingSetSize, int dwMaximumWorkingSetSize);

        [DllImport("KERNEL32.DLL", EntryPoint = "GetCurrentProcess", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
        internal static extern IntPtr GetCurrentProcess();

        private void nextItem()
        {
            try
            {
                //If You Want to define a defualt URI then you can define like below...
                if (activeLink != null)
                {
                    IntPtr pHandle = GetCurrentProcess();
                    SetProcessWorkingSetSize(pHandle, -1, -1);

                    string slink = "http://adf.ly/6446458/banner/" + activeLink.link;
                    wb.Source = new Uri(slink);
                    processBar.Value += 1;
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    
        private DateTime startTime;
        private void delay2second(Object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(2000);
            //while (true)
            //{

            //    TimeSpan time = DateTime.Now - startTime;

            //    if (time.Seconds > 2)
            //    {
            //        break;
            //    }

            //}
        }

        private void delay5second(Object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(5000);
            //while (true)
            //{

            //    TimeSpan time = DateTime.Now - startTime;

            //    if (time.Seconds > 5)
            //    {
            //        break;
            //    }

            //}
        }

        private void startDelayTonext()
        {
            startTime = DateTime.Now;
            BackgroundWorker thread = new BackgroundWorker();
            thread.DoWork += delay5second;
            thread.RunWorkerCompleted += StartNext;
            thread.WorkerReportsProgress = true;
            thread.WorkerSupportsCancellation = true;
            thread.RunWorkerAsync();
        }

        private void StartNext(Object sender, RunWorkerCompletedEventArgs e)
        {
            ListLinks.Remove(activeLink);

            if (ListLinks.Count > 0)
            {
                activeLink = ListLinks.ElementAt(0);
                nextItem();
            }
            else
            {
                this.Close();
            }
        }

        private void startThreadClick()
        {
            startTime = DateTime.Now;
            BackgroundWorker thread = new BackgroundWorker();
            thread.DoWork += delay2second;
            thread.RunWorkerCompleted += finishLogin;
            thread.WorkerReportsProgress = true;
            thread.WorkerSupportsCancellation = true;
            thread.RunWorkerAsync(); 
        }

        private void finishLogin(Object sender, RunWorkerCompletedEventArgs e)
        {
            if (!findButton())
            {
                startThreadClick();
            }
            else
            {
                startDelayTonext();
            }
        }

        private bool findButton()
        {
            //adfly_bar and last div
            var doc = (mshtml.HTMLDocument)wb.Document;

            if (doc != null)
            {
                mshtml.HTMLDivElement generatedLink = doc.getElementById("adfly_bar") as mshtml.HTMLDivElement;
                if (generatedLink != null)
                {
                    mshtml.HTMLDivElement closeBar = generatedLink.lastChild as mshtml.HTMLDivElement;
                    if (closeBar != null)
                    {
                        closeBar.click();
                       
                        return true;
                    }
                }
            }

            return false;
        }

        private void onLoadComplete(object sender, NavigationEventArgs e)
        {
            
        }

        private void onNavigated(object sender, NavigationEventArgs e)
        {
            string slink = "http://adf.ly/6446458/banner/" + activeLink.link;
            string sNaviageted = e.Uri.ToString();
            if(slink == sNaviageted)
                startThreadClick();
        }

        private void onLoad(object sender, RoutedEventArgs e)
        {

            if (connecttoServer())
            {
                if (ListLinks.Count > 0)
                {
                    activeLink = ListLinks.ElementAt(0);
                    nextItem();
                }
            }
        }

        private bool connecttoServer()
        {
            EntitiesAdfly db = new EntitiesAdfly();
            try
            {
                ListLinks = (from p in db.linkWebs select p).ToList();
                processBar.Maximum = ListLinks.Count;
                return true;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
           

            return false;
        }
       
    }
}
